<?php

namespace App\Models;

use App\Http\Helper\UrlSchemaHelper;
use App\Http\Helper\YunXinServerAPI;
use App\Models\Concerns\CommentTraits;
use App\Models\ProductRecordPicture;
use App\Models\ProductRecord;
use App\Models\Purchase;
use App\Models\Topic;
use App\Http\Controllers\Weixin\WechatTemplateController;

/**
 * Class Product
 * @property integer id
 * @property integer user_id
 * @property float price 价格
 * @property integer status 商品状态
 * @property string address 想去的地方
 * @property string act 行为(干什么)
 * @property string voice 语音介绍
 * @property integer voice_type 语音链接类型，1：微信，2：url
 * @property string type 商品类型
 * @property integer voice_length
 * @property date server_time
 * @property string server_day
 * @property string server_unit
 * @property integer channel
 * @property boolean allow_repeat 是否允许重复下单
 * @property boolean is_report 是否被举报
 * @property boolean is_down 语音是否被下载
 * @property integer skill_id 技能ID
 * @property integer sort 排序
 * @property integer skill_tag_id 技能标签ID
 * @property float level 星级评分
 * @property User user
 * @property Skill skill
 * @property SkillTag skillTag
 * @property Purchase purchases
 *
 */
class Product extends ApplicationModel
{
    use CommentTraits;


    protected $fillable = [
        'user_id',
        'price',
        'status',
        'address',
        'act',
        'voice',
        'server_time',
        'channel',
        'type',
        'voice_type',
        'voice_length',
        'allow_repeat',
        'skill_id',
        'level',
        'sort',
        'server_day',
        'is_report',
        'server_unit',
        'skill_tag_id',
        'tag_id',
        'tag_title',
        'location_status',
        'tag_sort'
    ];

    const STATUS_AUDITING = 1;//审核中
    const STATUS_RELEASE = 2;//已发布
    const STATUS_REJECT = 3;//拒绝中
    const STATUS_OFF = 4;//已接订单下架
    const STATUS_UPDATE_AUDING = 5; //修改审核中
    const STATUS_UPDATE_RELEASE = 6; //修改审核通过
    const STATUS_UPDATE_REJECT = 7; //修改审核拒绝

    static function boot()
    {
        parent::boot();
        static::updating(function (Product $product) {
            if ($product->isDirty('status') && $product->status == Product::STATUS_RELEASE) {
                if ($product->type == 'chuge') {
                    static::check_product($product);
                }
                if ($product->type == 'app') {
                    static::app_check_product($product);
                }
            }
            if ($product->isDirty('status') && $product->status == Product::STATUS_REJECT) {
                if ($product->type == 'chuge') {
                    static::reject_product($product);
                }
                if ($product->type == 'app') {
                    static::app_reject_product($product);
                }
            }

        });
    }

    /**
     * app审核通过通知
     * @param Product $product
     */
    public static function app_check_product(Product $product)
    {
        if(Product::release()->where('type','app')->where('skill_id',$product->skill_id)->count()>=5){
            Product::release()->where('type','import')->where('skill_id',$product->skill_id)->update(['status'=>static::STATUS_REJECT]);
        }
        $title = empty($product->skill)?$product->tag_title:$product->skill->title;
        $content = sprintf(Message::PRODUCT_SUCCESS, $title);
        $product->save_msg($content);
    }

    /**
     * app审核失败通知
     * @param Product $product
     */
    public static function app_reject_product(Product $product)
    {


        $title = empty($product->skill)?$product->tag_title:$product->skill->title;

        $push_content = sprintf(Message::PRODUCT_PUSH_REJECT, $title);
        $content = sprintf(Message::PRODUCT_REJECT, $title);
        $product->save_msg($content, $push_content);
    }

    /**
     * 保存消息并推送
     * @param $content
     */
    private function save_msg($content, $push_content = null)
    {
        $message = new Message();
        $message->user_id = $this->user_id;
        $message->content = $content;
        $message->icon = Message::ICON;
        $message->url_schema = UrlSchemaHelper::get_url_schema('myskill');
        $message->type_id = $this->id;
        $message->save();

        $url = UrlSchemaHelper::get_url_schema('myskill');

        $url = $push_content ? UrlSchemaHelper::get_url_schema('messages') : $url;
        \Log::info($url);
        //发送推送
        $message->pushMsg($this->user_id, $push_content ?: $content, "{'url':'" . $url . "'}");

        $yun = new YunXinServerAPI();
        $yun->pushTemplate($this->user->phone(), 3058250);
    }

    public static function reject_product($product)
    {
        $url = "https://apiv2test.superxing.cc/chuge";
        \Log::info($product->user->wx_user->open_id);
        $config = ['openid' => $product->user->wx_user->open_id, 'url' => $url];
        $data = array(
            "first"  => "很遗憾您发布的心愿没有通过审核，请重新发布",
            "keyword1"   => $product->user->name,
            "keyword2"   => "心愿",
            "keyword3"   => (string)$product->updated_at,
            "keyword4"   => "没有通过",
            "remark" => '点击详情查看',
        );
        WechatTemplateController::check_product($config, $data);
    }


    public static function check_product($product)
    {
        $url = "http://apiv2test.superxing.cc/chuge";
        \Log::info($product->user->wx_user->open_id);
        $config = ['openid' => $product->user->wx_user->open_id, 'url' => $url];
        $data = array(
            "first"  => "恭喜你发布的心愿已经通过审核",
            "keyword1"   => $product->user->name,
            "keyword2"   => "心愿",
            "keyword3"   => (string)$product->updated_at,
            "keyword4"   => "通过审核",
            "remark" => '点击详情查看',
        );
        WechatTemplateController::check_product($config, $data);
    }

    public function user_is_purchased($user)
    {
        if (!isset($user->id)) {
            return true;
        }
        $p = Purchase::where('product_id', $this->id)
            ->where('user_id', $user->id)
            ->whereNotIn('status', [3, 4, 7])
            ->count();
        if ($p > 0) {
            return false;
        }
        return true;
    }

    /**
     * 服务上架标识
     *
     */

    public function sale_flag()
    {
        $sale_flag = -1;
        if ($this->status == static::STATUS_AUDITING) {

        }
        if ($this->status == static::STATUS_RELEASE) {
           $sale_flag = 1;
        }
        if ($this->status == static::STATUS_REJECT) {
            $sale_flag = -1;
        }
        if ($this->status == static::STATUS_OFF) {
            $sale_flag = -1;
        }
        if ($this->status == static::STATUS_UPDATE_AUDING) {
            $sale_flag = 1;
        }
        if ($this->status == static::STATUS_UPDATE_RELEASE) {
            $sale_flag = 1;
        }
        if ($this->status == static::STATUS_UPDATE_REJECT) {
            $sale_flag = 1;
        }
        return $sale_flag;

    }

    public function status_desc()
    {
        if ($this->status == static::STATUS_AUDITING) {
            return "审核中，请您耐心等待";
        }
        if ($this->status == static::STATUS_RELEASE) {
            return "审核通过，服务已上架";
        }
        if ($this->status == static::STATUS_REJECT) {
            return "审核失败，请修改后再次提交";
        }
        if ($this->status == static::STATUS_OFF) {
            return "已接订单下架";
        }
        if ($this->status == static::STATUS_UPDATE_AUDING) {
            return "修改已提交，请耐心等待审核";
        }
        if ($this->status == static::STATUS_UPDATE_RELEASE) {
            return "审核通过，服务已上架";
        }
        if ($this->status == static::STATUS_UPDATE_REJECT) {
            return "修改审核未通过，请重新修改";
        }

    }

    public function scopeRelease($query)
    {
        return $query->where('products.status', static::STATUS_RELEASE)->where('products.is_report', false);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function pictures()
    {
        return $this->hasMany(Picture::class,'type_id')->where('type',$this->model_name());
    }
    public function recordpictures()
    {
        return $this->hasMany(ProductRecordPicture::class,'product_id')->where('type',$this->model_name());
    }
    public function purchases()
    {
        return $this->hasMany(Purchase::class)->where('status', '!=', Purchase::STATUS_WAITING)->orderBy('created_at', 'desc');
    }

    public function skill()
    {
        return $this->belongsTo(Skill::class)->withTrashed();
    }

    public function skillTag()
    {
        return $this->belongsTo(SkillTag::class)->withTrashed();
    }

    public function productRelations()
    {
        return $this->hasMany(ProductRelation::class);
    }

    public function productRemarks()
    {
        return $this->hasMany(ProductRemark::class);
    }

    public function productRecords()
    {
        return $this->hasMany(ProductRecord::class);
    }
    public function share_content()
    {
        $avatar = $this->user->avatar;
        $do_main = config('constants.DO_MAIN');
        $arr = array(
            'qqShare' => array('title' => '此人身怀绝技，正在贩卖“时间”，快来约！', 'content' => '快来CC星球约“' . $this->user->name . '”', 'url' => $do_main . '/app/download.html', 'cover' => ($avatar ? $avatar : 'https://img.superxing.cc/api/img/official_logo.png')),
            'wxShare' => array('title' => '此人身怀绝技，正在贩卖“时间”，快来约！', 'content' => '快来CC星球约“' . $this->user->name . '”', 'url' => $do_main . '/app/download.html', 'cover' => ($avatar ? $avatar : 'https://img.superxing.cc/api/img/official_logo.png')),
            'wxQuan' => array('title' => '此人身怀绝技，正在贩卖“时间”，快来约！', 'content' => '此人身怀绝技，正在贩卖“时间”，快来约！', 'url' => $do_main . '/app/download.html', 'cover' => ($avatar ? $avatar : 'https://img.superxing.cc/api/img/official_logo.png')),
            'wbShare' => array('title' => '此人身怀绝技，正在贩卖“时间”，快来约！', 'content' => '快来CC星球约“' . $this->user->name . '”', 'url' => $do_main . '/app/download.html', 'cover' => ($avatar ? $avatar : 'https://img.superxing.cc/api/img/official_logo.png')),
            'qqZone' => array('title' => '此人身怀绝技，正在贩卖“时间”，快来约！', 'content' => '快来CC星球约“' . $this->user->name . '”', 'url' => $do_main . '/app/download.html', 'cover' => ($avatar ? $avatar : 'https://img.superxing.cc/api/img/official_logo.png')),
        );

        return $arr;
    }

    public function discount_picture($user_id=0,$product_id=0)
    {
        $discount_picture = '';
        $product_topic_relation = $this->productRelations()->where('type', 'Topic')->orderBy('created_at', 'desc')->first();
        if($product_topic_relation)
        {
            $topic = $product_topic_relation->topic()->release()->first();
            if($topic)
            {
                $discount_picture = $topic->discount_picture;
                $first_discount_flag = $topic->first_discount_flag;
                if($first_discount_flag==1)
                {
                    $user_id = intval($user_id);
                    if( $user_id > 0 )
                    {
                        $p_count = Purchase::serving()->productType()->withTrashed()->where('user_id', $user_id)->where('product_id',$product_id)->count();
                        if ($p_count>0 )
                        {
                            $discount_picture = '';
                        }
                    }
                }

            }
        }
        return $discount_picture;

    }


    public function topic_discount_flag()
    {
        $discount_flag = 0;
        $product_relation = $this->productRelations()->where('type', 'Sale')->orderBy('created_at', 'desc')->first();
        if ($product_relation)
        {
            //获取优惠活动是否为进行中
            $sale = $product_relation->sale()->release()->first();
            if ($sale)
            {
                $discount_flag = 1;
            }

        }
        $product_topic_relation = $this->productRelations()->where('type', 'Topic')->orderBy('created_at', 'desc')->first();
       // \Log::info($product_topic_relation,['=============================topic=_relation===================================']);
        if($product_topic_relation)
        {
            $topic = $product_topic_relation->topic()->release()->first();
            if($topic)
            {
                $discount_flag = 1;
            }
        }
        return $discount_flag;
    }

    public function discount_flag($user_id=0,$product_id=0)
    {
        $discount_flag = 0;
        $product_topic_relation = $this->productRelations()->where('type', 'Topic')->orderBy('created_at', 'desc')->first();
        if($product_topic_relation)
        {
            $topic = $product_topic_relation->topic()->release()->first();
            if($topic)
            {
                $discount_flag = 1;
                $first_discount_flag = $topic->first_discount_flag;
                if($first_discount_flag==1)
                {
                    $user_id = intval($user_id);
                    if( $user_id > 0 )
                    {
                        $p_count = Purchase::serving()->productType()->withTrashed()->where('user_id', $user_id)->where('product_id',$product_id)->count();
                        if ($p_count>0 )
                        {
                            $discount_flag = 0;
                        }
                    }
                }
            }
        }
        return $discount_flag;
    }


    /**
     * 判断服务是否在参加优惠活动，如果参加否参加
     * @return float
     */
    public function first_discount_flag($user_id=0,$product_id=0)
    {
        $first_discount_flag = 0;
        $type = $this->discount_type();

        if( $type==1 )
        {
            $p_count = Purchase::serving()->productType()->withTrashed()->where('user_id', $user_id)->where('product_id',$this->id)->count();
            if( $p_count>0 )
            {

            }
            else
            {
               $first_discount_flag = 1;

            }
        }
        else if($type==2)
        {
            $p_count = Purchase::serving()->productType()->withTrashed()->where('user_id', $user_id)->count();
            if( $p_count>0 )
            {

            }
            else
            {
                $first_discount_flag = 1;

            }

        }


        return $first_discount_flag;
    }


    public function discount_type()
    {
        $type = -1; //该服务未优惠
        $product_topic_relation = $this->productRelations()->where('type', 'Topic')->orderBy('created_at', 'desc')->first();
        if($product_topic_relation)
        {
            $topic = $product_topic_relation->topic()->release()->first();
            if($topic)
            {
                $type = $topic->first_discount_flag;
            }

        }
        return $type;

    }
    /**
     * 服务优惠价格
     * @return float
     */
    public function discount_price($user_id=0,$purchase_id=0)
    {

        $product_relation = $this->productRelations()->where('type', 'Sale')->orderBy('created_at', 'desc')->first();
        if ($product_relation)
        {
            //获取优惠活动是否为进行中
            $sale = $product_relation->sale()->release()->first();
            if ($sale)
            {
                $p_count_sale = Purchase::serving()->productType()->withTrashed()->where('user_id', $user_id)->count();
                if( $p_count_sale > 0 )
                {

                }
                else
                {
                    return $sale->price;
                }

            }
        }
        $product_topic_relation = $this->productRelations()->where('type', 'Topic')->orderBy('created_at', 'desc')->first();
        if($product_topic_relation)
        {
            $topic = $product_topic_relation->topic()->release()->first();
            if($topic)
            {
                $first_discount_flag = $topic->first_discount_flag;

                if($first_discount_flag==1)
                {
                    $user_id = intval($user_id);
                    if( $user_id > 0 )
                    {
                        if($purchase_id>0)
                        {

                            $p_count = Purchase::serving()->productType()->withTrashed()->where('user_id', $user_id)->where('product_id',$this->id)->where('id','!=',$purchase_id)->count();

                        }
                        else
                        {
                            $p_count = Purchase::serving()->productType()->withTrashed()->where('user_id', $user_id)->where('product_id',$this->id)->count();
                        }

                        //\Log::info($p_count,['=============================p_count=====================================']);
                        if ($p_count>0 )
                        {
                            return $this->price;
                        }
                    }
                }
                else if( $first_discount_flag==2 )
                 {
                    $p_count = Purchase::serving()->productType()->withTrashed()->where('user_id', $user_id)->where('id','!=',$purchase_id)->count();
                    if( $p_count>0 )
                    {
                        return $this->price;
                    }
                    else
                    {
                        return $product_topic_relation->price;
                    }

                }
                else if( $first_discount_flag == 0)
                {
                    return $product_topic_relation->price;

                }
                else if( $first_discount_flag == 3)
                {
                    return $this->price;
                }
                return $product_topic_relation->price;
            }
        }

        return $this->price;
    }

    /**
     * 判断服务是否在参加优惠活动，如果参加则返回活动价格，未参加则返回服务价格
     * @return float
     */
    public function price()
    {
        //获取服务是否关联了优惠活动信息
        $product_relation = $this->productRelations()->where('type', 'Sale')->orderBy('created_at', 'desc')->first();
        if ($product_relation)
        {
            //获取优惠活动是否为进行中
            $sale = $product_relation->sale()->release()->first();
            if ($sale)
            {
                return $sale->price;
            }

        }
        $product_topic_relation = $this->productRelations()->where('type', 'Topic')->orderBy('created_at', 'desc')->first();
        if($product_topic_relation)
        {
            $topic = $product_topic_relation->topic()->release()->first();
            if($topic)
            {
               return $product_topic_relation->price;
            }
        }
        return $this->price;
    }

    public function is_topic()
    {
        //获取服务是否关联了优惠活动信息
        $product_relation = $this->productRelations()->where('type', 'Topic')->orderBy('created_at', 'desc')->first();

        if ($product_relation) {
            //获取优惠活动是否为进行中
            $topic = $product_relation->topic()->release()->first();
            if ($topic) {
                return true;
            }
        }
        return false;
    }



    /**
     * 判断服务是否在参加优惠活动
     * @return bool
     */
    public function is_sale()
    {
        //获取服务是否关联了优惠活动信息
        $product_relation = $this->productRelations()->where('type', 'Sale')->orderBy('created_at', 'desc')->first();
       // \Log::info( $product_relation,['=============================sale= product_relation==================================']);
        if ($product_relation)
        {
            //获取优惠活动是否为进行中
            $sale = $product_relation->sale()->release()->first();
            //\Log::info($sale,['=============================sale==sale===================================']);
            if ($sale) {
                return true;
            }
        }
        return false;
    }

    public function discount_limit_msg( $flag=2 )
    {
        $msg = "只有首次下单用户可享受此优惠哦，若想继续购买，需要按原价购买~";
        if( $flag==1 )
        {
            $msg = "在活动期间首次下单此服务的用户可以享受优惠，若想继续购买，需要按原价购买~";
        }
        return $msg;
    }
    /**
     * 判断用户是否限购提示
     * @return bool
     */
    public function discount_limit_flag($user_id=0)
    {
        $discount_limit_flag = -1;
        $product_relation = $this->productRelations()->where('type', 'Sale')->orderBy('created_at', 'desc')->first();
        if($product_relation)
        {
            if( $this->is_sale() && $user_id>0)
            {
                $p_count = Purchase::serving()->productType()->withTrashed()->where('user_id', $user_id)->count();
                if($p_count>0)
                {
                    return 1;
                }
            }
        }
        $product_topic_relation = $this->productRelations()->where('type', 'Topic')->orderBy('created_at', 'desc')->first();
        //\Log::info($topic,['=============================topic===================================']);
        if($product_topic_relation)
        {
            //$topic_test = $product_topic_relation->topic()->release()->first();
            $topic = $product_topic_relation->topic()->release()->first();
            if($topic)
            {
                $first_discount_flag = $topic->first_discount_flag;
                if( $first_discount_flag==1 )
                {
                    if( $this->is_topic() && $user_id>0 )
                    {

                        $p_count = Purchase::serving()->productType()->withTrashed()->where('user_id', $user_id)->where('product_id',$this->id)->count();
                        if($p_count>0)
                        {
                            return 1;
                        }
                    }
                }
                else if( $first_discount_flag == 2 )
                {

                    if( $this->is_topic() && $user_id>0)
                    {
                       // $p_count = Purchase::serving()->productType()->withTrashed()->where('user_id', $user_id)->where('product_id',$this->id)->count();
                        $p_count = Purchase::serving()->productType()->withTrashed()->where('user_id', $user_id)->count();
                        if($p_count>0)
                        {
                            return 1;
                        }
                    }
                }
            }
        }
        return $discount_limit_flag;


    }

    /**
     * 单位说明
     * @return string
     */
    public function server_unit_str()
    {
        switch ($this->server_unit) {
            case 1:
                return '小时';
            case 2:
                return '次';
            case 3:
                return '分钟';
        }
    }

    /**
     * 服务审核拒绝原因
     * @return sting
     */
    public function reject_reason_str()
    {

        $remark = "";
        if($this->status==3 || $this->status==7 )
        {
            if( $this->status==3 )
            {
                $type = 1;
                $product_remarks = $this->productRemarks()->where('type',$type)->where('product_id',$this->id)->orderBy('sort','ASC')->get();
            }
            else if( $this->status == 7 )
            {
                $type = 2;
                $product_record = ProductRecord::where('product_id',$this->id)->where('status',7)->orderBy('created_at','DESC')->first();
                if($product_record)
                {
                    $product_remarks = $this->productRemarks()->where('type',$type)->where('product_record_id',$product_record->id)->where('product_id',$this->id)->orderBy('sort','ASC')->get();
                }
                else
                {
                    $product_remarks = $this->productRemarks()->where('type',$type)->where('product_id',$this->id)->orderBy('sort','ASC')->get();
                }

            }

            if( count($product_remarks)>0 )
            {
                $remark = "拒绝原因:";
                $split = "\n";
                $count = count($product_remarks);
                foreach($product_remarks as $k=>$product_remark)
                {
                    if($k==$count-1)
                    {
                        $split = "";
                    }
                    $temp = $product_remark->remark;
                    $remark .=$temp.$split;
                }
            }
        }
        return $remark;
    }

    /**
     * 获取修改服务记录
     * @return
     */

    public function getProductRecord()
    {
        $product_record = $this->productRecords()->where('product_id',$this->id)->whereIn('status',[5,6,7])->orderBy('created_at','DESC')->first();
        return $product_record;
    }

    /**
     * 获取修改服务图片
     * @return
     */

    public function getProuctRecordPicture()
    {
        $product_record = $this->getProductRecord();
        $product_record_id = 0;
        if($product_record)
        {
            $product_record_id = $product_record->id;

        }
        $product_record_picture = null;
        if($product_record)
        {
            $product_record_picture = ProductRecordPicture::where('product_record_id',$product_record_id)->where('product_id',$this->id)->where('type','Product')->orderBy('id','DESC')->first();
        }
        return $product_record_picture;
    }

    public function update_auditing_info()
    {
        $returnArr = array();
        $returnArr['tag_title'] = $this->tag_title;
        $returnArr['act'] = $this->act;
        $returnArr['picture'] = '';
        $original_picture = $this->pictures()->where('type','Product')->where('type_id',$this->id)->orderBy('sort','ASC')->first();
        if($original_picture)
        {
            $returnArr['picture'] = $original_picture->original_url;
        }
        if( $this->status==5 )
        {
            $product_record = $this->productRecords()->where('product_id',$this->id)->orderBy('created_at','DESC')->first();
            if($product_record)
            {
                $product_record_picture = ProductRecordPicture::where('product_record_id',$product_record->id)->where('product_id',$this->id)->where('type','Product')->orderBy('sort','ASC')->first();
                if( $product_record->update_service_flag==1 )
                {
                    $returnArr['tag_title'] = $product_record->tag_title;
                }
                if( $product_record->update_picture_flag==1 )
                {
                    if($product_record_picture)
                    {
                        $returnArr['picture'] = $product_record_picture->original_url;
                    }
                }
                if( $product_record->update_act_flag==1 )
                {
                    $returnArr['act'] = $product_record->tag_title;
                }
            }
        }
        return $returnArr;
    }


    public function update_auditing_desc()
    {

        $returnArr = array();
        $returnArr['update_service_desc'] = '';
        $returnArr['update_picture_desc'] = '';
        $returnArr['update_act_desc'] = '';
        $message = '修改已提交，请耐心等待审核';
        if( $this->status==5 )
        {
            $product_record = $this->productRecords()->where('product_id',$this->id)->orderBy('created_at','DESC')->first();
            if($product_record)
            {
                if( $product_record->update_service_flag==1 )
                {
                    $returnArr['update_service_desc'] = $message;
                }
                if( $product_record->update_picture_flag==1 )
                {
                    $returnArr['update_picture_desc'] = $message;
                }

                if( $product_record->update_act_flag==1 )
                {
                    $returnArr['update_act_desc'] = $message;
                }
            }

        }
        return $returnArr;

    }



}
